﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using com.hebg3.usb.watcher.impl;
using com.hebg3.usb.query.impl;
using System.Management;
using com.hebg3.shell;
using com.hebg3.usb.enumerate;
using com.hebg3.cmd;

namespace com.hebg3.ui {
  public partial class FormUsb :Form {
    private WMIUsbWatcher usbWatcher = new WMIUsbWatcher();
    public FormUsb() {
      InitializeComponent();
    }

    private void FormUsb_Load(object sender, EventArgs e) {
      usbWatcher.AddUSBEventWatcher(USBEventHandler, USBEventHandler, new TimeSpan(0, 0, 3));
      
    }

    private void button1_Click(object sender, EventArgs e) {
      PnPEntityInfo[] usbs = new PnPEntityInfo[10];
      //USBQuery usbq = new USBQuery();
      usbs = WMIUsbQuery.AllPnPEntities;

      foreach( PnPEntityInfo ei in usbs ) {
        Console.WriteLine(ei.PNPDeviceID);
        listBox1.Items.Add(ei.VendorID);
      }
    }

    private void button4_Click(object sender, EventArgs e) {

    }


    private void USBEventHandler(Object sender, EventArrivedEventArgs e) {
      if( e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent" ) {
        this.SetText("USB插入时间：" + DateTime.Now + "\r\n");
      } else if( e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent" ) {
        this.SetText("USB拔出时间：" + DateTime.Now + "\r\n");
      }

      foreach( USBControllerDevice Device in WMIUsbWatcher.WhoUSBControllerDevice(e) ) {
        this.SetText("\tAntecedent：" + Device.Antecedent + "\r\n");
        this.SetText("\tDependent：" + Device.Dependent + "\r\n");
      }
    }
    // 对 Windows 窗体控件进行线程安全调用   
    private void SetText(String text) {
      if( this.textBox1.InvokeRequired ) {
        this.textBox1.BeginInvoke(new Action<String>((msg) => {
          this.textBox1.AppendText(msg);
        }), text);
      } else {
        this.textBox1.AppendText(text);
      }
    }

    private void button2_Click(object sender, EventArgs e) {
      //textBox2.AppendText(CommandDo.Execute("dir"));
      //textBox2.AppendText(CommandDo.Execute("dir"));
    }

    private void button3_Click(object sender, EventArgs e) {
      this.skinEngine1.SkinFile = "CalmnessColor1.ssk";
    }

    private void FormUsb_FormClosing(object sender, FormClosingEventArgs e) {
      usbWatcher.RemoveUSBEventWatcher();
    }
  }
}
